/**
 * 集合
 * capacity: 底层哈希表的初始容量
 */
func Set(capacity) {
    if (capacity == null) {
        capacity = 10
    }

    var elems = []
    for (var i = 0; i < capacity; ++i) {
        elems.addLast([])
    }

    var size = 0

    func getHashCode(obj) {
        var hashCode = hashCode(obj)
        if (hashCode < 0) {
            return -hashCode
        }
        return hashCode
    }

    return {
        // 将元素添加到集合
        add(e) {
            var hashCode = getHashCode(e)
            var index = hashCode % capacity
            for (var i = 0; i < elems[index].length(); ++i) {
                if (getHashCode(elems[index][i]) == hashCode) {
                    return
                }
            }
            elems[index].addFirst(e)
            size++
        },
        // 移除集合中的元素
        remove(e) {
            var hashCode = getHashCode(e)
            var index = (hashCode + capacity) % capacity
            for (var i = 0; i < elems[index].length(); ++i) {
                if (getHashCode(elems[index][i]) == hashCode) {
                    elems[index].remove(i)
                    size--
                    return true
                }
            }
            return false
        },
        // 判断集合是否存在元素
        contains(e) {
            var hashCode = getHashCode(e)
            var index = (hashCode + capacity) % capacity
            for (var i = 0; i < elems[index].length(); ++i) {
                if (getHashCode(elems[index][i]) == hashCode) {
                    return true
                }
            }
            return false
        },
        // 获取元素个数
        size() {
            return size
        },
        // 是否为空
        isEmpty() {
            return size == 0
        },
        // 转换为列表
        toList() {
            var result = []
            for (var i = 0; i < elems.length(); ++i) {
                for (var j = 0; j < elems[i].length(); ++j) {
                    result.addLast(elems[i][j])
                }
            }
            return result
        }
    }
}
